package com.sysd.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;

/**
 * @description: 服务器，初始化的时候自动启动
 * @author: bsh
 * @date: 2025/6/5 09:04
 */
@Component
public class NettyServer {
    private final WebSocketChannelInitializer webSocketChannelInitializer;
    private final ExecutorService executorService;
    /**
     * get listen port number
     */
    @Value("${netty.server.port}")
    private int port;

    private final int boosThread = 1;

    private final int workThread = 2;

    public NettyServer(WebSocketChannelInitializer webSocketChannelInitializer, ExecutorService executorService) {
        this.webSocketChannelInitializer = webSocketChannelInitializer;
        this.executorService = executorService;
        this.init();
    }

    public void init() {
        this.executorService.submit(() -> {
            NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
            NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);
            try {
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap
                        .group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .option(ChannelOption.SO_BACKLOG, 128)
                        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                        .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                        .handler(new LoggingHandler(LogLevel.DEBUG))
                        .childHandler(webSocketChannelInitializer);
                ChannelFuture future = serverBootstrap.bind(port).sync();
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
                System.out.println("启动成功!");
            }
        });

    }
}
